package com.wf.ew.JTServer.common.db;

import com.wf.ew.JTServer.common.packet.JT809Packet0x1202;
import com.wf.ew.common.utils.DateUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.UUID;


/**
 * @Author: Xiuming Lee
 * @Date: 2019/9/26 18:48
 * @Version 1.0
 * @Describe:
 */
@Repository
public class JT809Dao {
	private static Logger log = LoggerFactory.getLogger(JT809Dao.class);
	public static int insert0x1202(JT809Packet0x1202 packet) {
		QueryRunner runner = new QueryRunner();
		Connection conn = DataSourceConnectionFactory.getDbConnection();
		StringBuffer sql1 =new StringBuffer("DELETE FROM sszg_cargps WHERE vehicleno = ? ");
		StringBuffer sql =new StringBuffer("insert into sszg_cargps (");
		sql.append("id,vehicleno,lon,lat,sendtime");
		sql.append(",cjsj,vec1,vec2,vec3,direction");
		sql.append(",altitude,alarm,createUser) values ( ");
		sql.append("?,?,?,?,?,");
		sql.append("?,?,?,?,?,");
		sql.append("?,?,?)");
		int insert = 0;
		try {
			runner.update(conn, sql1.toString(), packet.getVehicleNo().replaceAll("\u0000", ""));
			insert = runner.update(conn, sql.toString(), UUID.randomUUID().toString().replace("-", ""),
					packet.getVehicleNo().replaceAll("\u0000", ""),
					String.format("%.6f", packet.getLon() * 1e-6),
					String.format("%.6f", packet.getLat() * 1e-6), DateUtil.formatDate(LocalDateTime.of(packet.getDate(), packet.getTime())),
					DateUtil.getCurrentDate(), packet.getVec1(), packet.getVec2(), packet.getVec3(), packet.getDirection(),
					packet.getAltitude(), packet.getAlarm(),"1");
			log.info("delete sql:" + sql1.toString());
			log.info("add sql:" + sql.toString());
		} catch (SQLException e) {
			log.info("数据存储错误：{}", e.getMessage());
		}
		return insert;

	}

	public static int delYesterdayData() {
		QueryRunner runner = new QueryRunner();
		Connection conn = DataSourceConnectionFactory.getDbConnection();
		String sql = "DELETE FROM sszg_cargps WHERE sendtime < CURRENT_DATE";
		int del = 0;
		try {
			del = runner.update(conn, sql);
			log.info("DELETE sql:" + sql.toString());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return del;
	}

	public static void getMapParameter(StringBuffer sql, Map<String, String> args){
		StringBuffer s = new StringBuffer();
		if(null!=args){
			for (Map.Entry<String, String> entry : args.entrySet()) {
				if(s.length()>0){s.append(",");}
				s.append(entry.getKey() + ":" + entry.getValue());
			}
		}
		log.info("时间:{}\n SQL:{}\n 参数:{}", DateUtil.getCurrentDate(), sql.toString(), s);
//		System.out.println(DateUtil.getCurrentDate());
//		System.out.println(sql.toString());
//		System.out.println(s);
	}
}
